package com.JZ.QM.utils;

import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cyc
 * @email cyc@gmail.com
 * @date 2020/6/24 09:37
 */
public class RealNameAuthentication {
    /**
     *发送身份证号码与姓名，返回结果集
     * @param idCard
     * @param name
     * @return
     * @throws IOException
     */
    public static HashMap getResult(String idCard,String name) throws IOException, JSONException {
        //根据姓名与身份证号获取返回的字符串
        String result = postForm(idCard,name);
        System.out.println(result);
        return getState(result);
    }

    /**
     * 发送请求进行实名认证
     * @param idCard
     * @param name
     * @return
     * @throws IOException
     */
    public static String postForm(String idCard,String name) throws IOException {
        //请求连接
        String url = "https://eid.shumaidata.com/eid/check";
        //用户的appCode
        String appCode = "a5e9ee7cc9f54b5994d723a789fdbf2f";
        //参数封装
        Map<String, String> params = new HashMap();
        //构造请求连接
        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();


        params.put("idcard", idCard);
        params.put("name", name);
        formbuilder.add("idcard",params.get("idcard"));
        formbuilder.add("name",params.get("name"));
        //请求体参数
        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(body).build();
        Response response = client.newCall(request).execute();
        System.out.println("返回状态码" + response.code() + ",message:" +  response.message());
        String result = response.body().string();
        return result;
    }

    /**
     * 讲字符串解析为json格式
     * @param result
     * @return 返回以HashMap封装的结果集
     */
    public static HashMap<String,Object> getState(String result) throws JSONException {
        //将String对象转换为json对象
        JSONObject json=new JSONObject(result);
        //json详细的返回信息
        JSONObject  detail;
        //返回结果HashMap
        HashMap<String,Object> stateRes=new HashMap();
        //记录返回状态
        int code=Integer.parseInt(json.get("code").toString());

        if (code == 0){
            detail= new JSONObject(json.get("result").toString());
            if(Integer.parseInt(detail.get("res").toString()) == 1){
                stateRes.put("state",true);
                stateRes.put("description",detail.get("description"));
                stateRes.put("address",detail.get("address"));
            }else{
                stateRes.put("state",false);
                stateRes.put("description",detail.get("description"));
            }
        } else {
            stateRes.put("state",false);
            stateRes.put("description",json.get("message"));
        }
        return stateRes;
    }
}